﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Dmtp.FileTransfer;
using TouchSocket.Dmtp.Rpc;
using TouchSocket.Sockets;

namespace Teriri.File.Client.Function
{
    public class FileManageFunction
    {
        public static List<FileInfoDto> GetFilesAndFolders(string remoteIPHost, string verifyToken, string path)
        {
            var client = RpcClientHelper.GetClient(remoteIPHost, verifyToken);
            var res = client.GetDmtpRpcActor().InvokeResult<List<FileInfoDto>>("FileManage_GetFilesAndFolders", path);
            if (res.Succ == false)
                throw new Exception(res.Message);

            return res.Result;
        }

        public static void CreateFolder(string remoteIPHost, string verifyToken, string path, string folderName)
        {
            var client = RpcClientHelper.GetClient(remoteIPHost, verifyToken);
            var res = client.GetDmtpRpcActor().InvokeResult<string>("FileManage_CreateFolder", path, folderName);
            if (res.Succ == false)
                throw new Exception(res.Message);
        }

        public static void DecompressingFile(string remoteIPHost, string verifyToken, string path)
        {
            var client = RpcClientHelper.GetClient(remoteIPHost, verifyToken);
            var res = client.GetDmtpRpcActor().InvokeResult<string>("FileManage_DecompressingFile", path);
            if (res.Succ == false)
                throw new Exception(res.Message);
        }

        public static string GetRootPath(string remoteIPHost, string verifyToken)
        {
            var client = RpcClientHelper.GetClient(remoteIPHost, verifyToken);
            var res = client.GetDmtpRpcActor().InvokeResult<string>("FileManage_GetRootPath");
            if (res.Succ == false)
                throw new Exception(res.Message);

            return res.Result;
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="remoteIPHost"></param>
        /// <param name="verifyToken"></param>
        /// <param name="filePath"></param>
        /// <param name="saveFilePath"></param>
        /// <param name="rootPath"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public static Task DownloadFile(string remoteIPHost, string verifyToken, string filePath, string saveFilePath, string rootPath , Action<float,long> action = null)
        {
            var client = RpcClientHelper.GetClient(remoteIPHost, verifyToken);

            client.GetDmtpFileTransferActor().RootPath = rootPath;

            var metadata = new Metadata();//传递到服务器的元数据
            metadata.Add("1", "1");
            metadata.Add("2", "2");

            var fileOperator = new FileOperator//实例化本次传输的控制器，用于获取传输进度、速度、状态等。
            {
                SavePath = saveFilePath,//客户端本地保存路径
                ResourcePath = filePath,//请求文件的资源路径
                Metadata = metadata,//传递到服务器的元数据
                Timeout = TimeSpan.FromSeconds(60),//传输超时时长
                TryCount = 10,//当遇到失败时，尝试次数
                FileSectionSize = 1024 * 128, //分包大小，当网络较差时，应该适当减小该值
            };

            fileOperator.MaxSpeed = 1024 * 1024 * 10;//设置最大限速为10Mb。

            // 此处的作用相当于Timer，定时每秒输出当前的传输进度和速度。
            if(action != null)
            {
                var loopAction = LoopAction.CreateLoopAction(-1, 1000, (loop) =>
                {
                    if (fileOperator.Result.ResultCode != ResultCode.Default)
                        loop.Dispose();

                    action.Invoke(fileOperator.Progress, fileOperator.Speed());
                });

                loopAction.RunAsync();
            }

            return client.GetDmtpFileTransferActor().PullFileAsync(fileOperator);
        }
    
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="remoteIPHost"></param>
        /// <param name="verifyToken"></param>
        /// <param name="filePath"></param>
        /// <param name="saveFilePath"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public static Task UploadFile(string remoteIPHost, string verifyToken, string filePath, string saveFilePath, Action<float, long> action = null)
        {
            var client = RpcClientHelper.GetClient(remoteIPHost, verifyToken);

            var metadata = new Metadata();//传递到服务器的元数据

            var fileOperator = new FileOperator//实例化本次传输的控制器，用于获取传输进度、速度、状态等。
            {
                SavePath = saveFilePath,//服务器本地保存路径
                ResourcePath = filePath,//客户端本地即将上传文件的资源路径
                Metadata = metadata,//传递到服务器的元数据
                Timeout = TimeSpan.FromSeconds(60),//传输超时时长
                TryCount = 10,//当遇到失败时，尝试次数
                FileSectionSize = 1024 * 256//分包大小，当网络较差时，应该适当减小该值
            };

            fileOperator.MaxSpeed = 1024 * 1024 * 10;//设置最大限速为10Mb。

            //此处的作用相当于Timer，定时每秒输出当前的传输进度和速度。
            var loopAction = LoopAction.CreateLoopAction(-1, 1000, (loop) =>
            {
                if (fileOperator.Result.ResultCode != ResultCode.Default)
                {
                    loop.Dispose();
                }

                action.Invoke(fileOperator.Progress, fileOperator.Speed());
            });

            loopAction.RunAsync();

            //此方法会阻塞，直到传输结束，也可以使用PushFileAsync
            return client.GetDmtpFileTransferActor().PushFileAsync(fileOperator);
        }
    }
}
